package com.xw.bo.ks.config;

import com.alibaba.fastjson.JSON;
import com.xw.bo.ks.client.RedisClient;
import com.xw.bo.ks.controller.BaseController;
import com.xw.bo.ks.entity.base.HeadData;
import com.xw.bo.ks.entity.enums.ExceptionEnum;
import com.xw.bo.ks.entity.exception.BoException;
import com.xw.bo.ks.util.AESUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 权限配置
 * @author xw
 */
@Slf4j
@Component
public class CommonInterceptor  implements HandlerInterceptor {

    @Resource
    private RedisClient redisClient;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler) throws Exception {

        String requestURI = httpServletRequest.getRequestURI();
        String token = httpServletRequest.getHeader("token");
        // 授权接口，不在请求头的统一处理中
        if ("/ks/postTokenByCode".contentEquals(requestURI)){
            String dsAuth = httpServletRequest.getHeader("Ds-Auth");

            HeadData headData = new HeadData();
            headData.setId(-1);
            headData.setRequestId("-1-1-1-1");
            BaseController.headDataLocal.set(headData);
            BaseController.dsAuth.set(dsAuth);
            BaseController.token.set(token);
            return true;
        }

        // 解密后的明文
        String authAes = getDsAuthAes(httpServletRequest);
        BaseController.token.set(token);
        BaseController.headDataLocal.set(getDsAuthAes(authAes));
        BaseController.dsAuth.set(authAes);
        return true;
    }

    /**
     * aes解密请求头DsAuth中的密文
     *
     * @return 明文
     */
    public String getDsAuthAes(HttpServletRequest servletRequest) {

        String dsAuthAes = servletRequest.getHeader("Ds-Auth");
        String dsAuth = "";

        if (StringUtils.isEmpty(dsAuthAes)){
            log.info("head Ds-Auth 密文: isEmpty,url:{}",servletRequest.getRequestURI());
            return dsAuth;
        }

        try {
            dsAuth = AESUtil.decrypt(dsAuthAes);
            log.info("head Ds-Auth 密文：{}", dsAuthAes);
            log.info("head Ds-Auth 解密：{}", dsAuth);
        } catch (Exception e) {
            log.info("head Ds-Auth 解密失败，接口：{},获取到的密文 = {}", servletRequest.getRequestURL(), dsAuthAes);
            throw new BoException(ExceptionEnum.AES_DECRYPT_EXCEPTION);
        }
        return dsAuth;
    }


    public HeadData getDsAuthAes(String dsAuth) {
        return JSON.parseObject(dsAuth, HeadData.class);
    }


}
